package com.integrate.kafka.porducer;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.admin.NewTopic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;

/**
 * @author 刘志强
 * @date 2020/11/13 13:50
 */
@Component
@Slf4j
public class KafkaProducer {

    @Autowired
    private KafkaTemplate<String, Object> kafkaTemplate;

    @Autowired
    @Qualifier("test_01")
    private NewTopic newTopic;

    public void send(Object obj) {
        //发送消息
        ListenableFuture<SendResult<String, Object>> future = kafkaTemplate.send(newTopic.name(), obj);
        future.addCallback(new ListenableFutureCallback<SendResult<String, Object>>() {
            @Override
            public void onFailure(Throwable throwable) {
                //发送失败的处理
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append(newTopic.name()).append(" - 生产者 发送消息失败：").append(throwable.getMessage());
                log.info(stringBuilder.toString());
            }

            @Override
            public void onSuccess(SendResult<String, Object> stringObjectSendResult) {
                //成功的处理
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append(newTopic.name()).append(" - 生产者 发送消息成功：").append(stringObjectSendResult.toString());
                log.info(stringBuilder.toString());
            }
        });
    }
}
